package net.xdclass.forum.service.impl;

import net.xdclass.forum.dao.CategoryDao;
import net.xdclass.forum.dao.TopicDao;
import net.xdclass.forum.domain.Category;
import net.xdclass.forum.domain.Topic;
import net.xdclass.forum.domain.User;
import net.xdclass.forum.dto.PageDTO;
import net.xdclass.forum.service.TopicService;

import java.util.Date;
import java.util.List;


public class TopicServiceImpl implements TopicService {

    private TopicDao topicDao = new TopicDao();
    private CategoryDao categoryDao = new CategoryDao();

    @Override
    public PageDTO<Topic> list(int cId, int page, int pageSize) {
        // 获取总行数
        int totalRecord = topicDao.countTotalRecord(cId);
        // 获取起始条数
        int from = (page - 1) * pageSize;
        List<Topic> list = topicDao.topicListByid(cId, from, pageSize);
        PageDTO<Topic> pageDTO = new PageDTO<>(page, pageSize, totalRecord);
        pageDTO.setList(list);
        return pageDTO;
    }

    @Override
    public Topic findTopicById(int topicId) {
        Topic topic = topicDao.findTopicById(topicId);
        return topic;
    }

    @Override
    public int addTopic(User user, int cId, String title, String content) {
        Category category = categoryDao.findByid(cId);
        if (category == null) {
            return 0;
        }
        Topic topic = new Topic();
        topic.setTitle(title);
        topic.setContent(content);
        topic.setCreateTime(new Date());
        topic.setUpdateTime(new Date());
        topic.setPv(1);
        topic.setDelete(0);
        topic.setUserId(user.getId());
        topic.setUsername(user.getUsername());
        topic.setUserImg(user.getImg());
        topic.setcId(cId);
        topic.setHot(0);
        int rows = 0;
        try {
            rows = topicDao.addTopic(topic);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rows;

    }

    @Override
    public void addOnePv(int topicId) {
        Topic topic = topicDao.findTopicById(topicId);
        int newPV = topic.getPv()+1;
        topicDao.addOnePv(topicId,newPV,topic.getPv());
    }
}
